<template>
	<view class="amap-choose">
<!--    <view class="top-button-succes">-->
<!--      &lt;!&ndash;			<text class="cancel" @tap="toCancel">取消</text>&ndash;&gt;-->
<!--      <text class="conform" :style="{'backgroundColor': color}" @tap="confrom">完成</text>-->
<!--    </view>-->
		<view class="top-button">
<!--			<text class="cancel" @tap="toCancel">取消</text>-->
			<text class="conform" :style="{'backgroundColor': '#fff'}" @tap="getcurrent"><image src="./loaction.png" class="locations"></image></text>
		</view>
		<view class="map-box">
			<view id="map"></view>
		</view>
		<view class="content">
			<view class="search">
				<view>
					<image src="./search.png"></image>
					<input placeholder="搜索地点"  @input="inputValue" v-model="keyword"/>
				</view>
				<text @tap="cancel">取消</text>
			</view>
			<view class="main">
				<view v-for="(item, index) in list" :key="index" @tap="toChecked(item)">
					<view>
						<view>{{item.name}}</view>
						<text class="detail">{{item.district}}{{item.address ? '-' + item.address : ''}}</text>
					</view>
					<view>
						<text :style="{color}" v-if="item.location === checked.location || checked.name === item.name">√</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default{
		props:{
			color: {
				type: String,
				default: '#ff6000'
			},
			keyMap: {
				type: String,
				default: ''
			},
			AMapKeyWeb: {
				type: String,
				default: ''
			},
			initLocation: {
				type: String,
				default: ''
			},
      initLocationall: {
        type: Object,
        default: {}
      },
			show: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				list: [],
				keyword: '',
				timeId: null,
				checked: {
					locaiton: ''
				},
				showPlace: false,
        myloaction:{},
			}
		},
		mounted() {
      var that = this;
			this.showPlace = this.show;
      window.onLoad  = function(){
        that.loop();
      }
      var url =  `https://webapi.amap.com/maps?v=2.0&key=${this.keyMap}&callback=onLoad`;
      var jsapi = document.createElement('script');
      jsapi.charset = 'utf-8';
      jsapi.src = url;
      document.head.appendChild(jsapi);
			// var script = document.getElementById('mapTest')
			// let that = this;
			// script ? this.loop() :
      //     (function (){
      // var script = document.createElement("script");
      // script.type = "text/javascript";
      // script.setAttribute('id', 'mapTest')
      // script.src = `https://webapi.amap.com/maps?v=2.0&key=${this.keyMap}`;
      // document.body.appendChild(script);
			// })()
		},
		watch: {
			// show(newVal, oldVal) {
			// 	this.showPlace = newVal;
			// 	this.$nextTick(() => {
			// 		this.loop();
			// 	})
			// }
		},
		methods:{
			loop() {
        console.log("=========1111loop")
				try{
					this.initMapWeb();
				}catch(e){
					setTimeout(()=>this.loop(), 200)
				}
			},

			inputValue(e) {
				if(this.timeId) {
					clearTimeout(this.timeId)
				}

				this.timeId = setTimeout(() => {
					this.getPlaces(e.detail.value, '')
					this.timeId = null
				})
			},

			cancel() {
				this.keyword = '';
				this.list = [];
				if(this.maker) {
					this.marker.setMap(null);
				}
			},

			toCancel() {
				this.cancel();
				this.$emit('changeShow', false)
			},
			//回到当前定位
      getcurrent() {
        this.checked = this.myloaction
        this.toChecked(this.myloaction)
        this.getNowPlaceFirst(this.myloaction.location);
			},
      confrom(){
        if(!this.checked.location){
          this.checked = this.myloaction
        }
        if(this.checked.location) {
        	let location = this.checked.location.split(',');
          let params = Object.assign(this.checked,{poiname:this.checked.name, adcode: this.checked.adcode, latitude:location[1], longitude:location[0],city:this.checked.city,province:this.checked.province,poiaddress:this.checked.district})
          this.$emit('placeChoose', params)
        }
      },
			toChecked(obj) {
				this.checked = obj;
        this.checked.poiaddress = this.checked.district;
        this.checked.poiname = this.checked.name
			  this.zhuanhuanCheck();
				if(this.marker) {
					this.marker.setMap(null);
					let tempArr = obj.location.split(',');
					this.addMarker(tempArr[0], tempArr[1])
				}
			},
      zhuanhuanCheck(){
        let copyAddress = this.checked.district
        var reg = /.+?(省|市|自治区|自治州|县|区)/g; // 省市区的正则
        this.checked.city = copyAddress.match(reg)[1]
        this.checked.province = copyAddress.match(reg)[0];
        console.log(copyAddress.match(reg),'this.checked:',this.checked);
      },
			initMapWeb() {
				let that = this;
        if(that.initLocation){
          that.checked = JSON.parse(JSON.stringify(this.initLocationall))
          that.checked.location = this.initLocation;
          that.checked.poiaddress = this.checked.district;
          that.checked.poiname = this.checked.name
        }
        that.map = new AMap.Map("map", {
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          zoomToAccuracy: true,
          zoom: 15,
          scrollWheel: false,
          dragEnable: true, //是否可拖动
          resizeEnable: true,
          rotateEnable: true,
				});

        that.map.on('click', (e) => {
					if(that.marker) {
            that.marker.setMap(null);
					}
					that.addMarker(e.lnglat.lng, e.lnglat.lat);
				  that.getNowPlace(`${e.lnglat.lng}, ${e.lnglat.lat}`);
				})
        that.getlocation();
			},
      getlocation(){
        let that = this;
        AMap.plugin('AMap.Geolocation', function() {
          uni.showLoading({
            title: '系统正在定位'
          });
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            buttonPosition: 'RB', //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
          });
          geolocation.getCurrentPosition(function(status, result) {
            if (status == 'complete'&&result.info == "SUCCESS" && result.position && result.position) {
              //这个地方的result，可能会出现报错：获得地理定位时间。得到ipLocation成功。获取地址失败，请检查您的密钥或网络。
              //可能是密匙申请错了，重新申请密匙，生成maps.js文件。
              console.log(result)
              uni.hideLoading();
              if(!that.initLocation){
                that.addMarker(result.position.lng, result.position.lat)
              }
              that.getNowPlaceFirst(`${result.position.lng}, ${result.position.lat}`);
            } else {
              uni.hideLoading();
              uni.showToast({
                title: '定位失败',
              });
              that.getNowPlaceFirst(`113.665412,34.757975`);
            }
          });
        });
      },
      getNowPlaceFirst(location) {
			  var that = this;
        location = location.replace(/[ ]/g,'');
        uni.request({
          url: `https://restapi.amap.com/v3/geocode/regeo?key=${this.AMapKeyWeb}&location=${location}`,
          method: 'GET',
          success: (res) => {
            let result = res.data;
            if(result.status == '1') {
              let tempObj = result.regeocode;
              this.myloaction = {
                adcode: tempObj.addressComponent.adcode,
                city: tempObj.addressComponent.city,
                province:tempObj.addressComponent.province,
                district: tempObj.addressComponent.province+tempObj.addressComponent.city+tempObj.addressComponent.district,
                location,
                addressLocal: '我的位置',
                address:tempObj.addressComponent.streetNumber.street+tempObj.addressComponent.streetNumber.number,
                id:'',
                name:'我的位置',
                poiaddress: tempObj.addressComponent.province+tempObj.addressComponent.city+tempObj.addressComponent.district,
                poiname:'我的位置',
                typecode:''
              }
              if(that.initLocation.length > 0) {
                let tempArr = this.initLocation.split(',');
                that.addMarker(tempArr[0], tempArr[1])
                that.getNowPlace(`${tempArr[0]}, ${tempArr[1]}`);
              }else{
                this.getPlaces(tempObj.formatted_address, '')
              }
            }
          },
          fail: (err) => {
            uni.showToast({
              title: JSON.stringify(err),
              icon: 'none'
            })
          }
        })
      },
			getNowPlace(location) {
			 location = location.replace(/[ ]/g,'');
			 uni.request({
					url: `https://restapi.amap.com/v3/geocode/regeo?key=${this.AMapKeyWeb}&location=${location}`,
					method: 'GET',
					success: (res) => {
						let result = res.data;
						if(result.status == '1') {
							let tempObj = result.regeocode;
              this.getPlaces(tempObj.formatted_address, '')
						}

					},
					fail: (err) => {
						uni.showToast({
							title: JSON.stringify(err),
							icon: 'none'
						})
					}
				})
			},

			addMarker(lng, lat) {
				var icon = new AMap.Icon({
					// 图标的取图地址
					image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
					// 图标所用图片大小
					imageSize: new AMap.Size(32, 42),
				});

				this.marker = new AMap.Marker({
					icon,
				    position: [lng, lat],
				});

				this.marker.setMap(this.map);
				this.map.setCenter([lng, lat])
			},

			getPlaces(keywords, location) {
			  var that = this;
        uni.request({
          url: `https://restapi.amap.com/v3/assistant/inputtips?key=${this.AMapKeyWeb}&keywords=${keywords}&location=${location}`,
          method: 'GET',
          success: (res) => {
            console.log('res:',res)
            let result = res.data;
            if(result.status === '1')  {
              that.list = []
              that.list = result.tips.filter(item => item.location && item.location.length > 0);
              // that.list.unshift(that.myloaction)
              console.log("this.checked:",this.checked,'list:',this.list, 'result.tips:',result.tips)
            }
          },
          fail: (err) => {
            uni.showToast({
              title: JSON.stringify(err),
              icon: 'none'
            })
          }
        })
			},
		}
	}
</script>

<style lang="scss" scoped>
	.amap-choose {
		position: fixed;
		top: 88rpx;
		width: 100%;
		height: 100vh;
		z-index: 969;
    .top-button-succes{
      top: 0px;
      right: 9%;
      position: fixed;
      box-sizing: border-box;
      padding: 24rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-end;
      z-index: 1000;
      .cancel {
        // color: white;
        background-color: #fafafa;
        padding: 8rpx 14rpx;
        border-radius: 8rpx;
      }
      .conform {
        border-radius: 6rpx;
        color:#Fff;
        padding: 6rpx 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
		.top-button {
      top: 51%;
      right: 3%;
			box-sizing: border-box;
			padding: 24rpx;
			position: fixed;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: flex-end;
			z-index: 100;
			.cancel {
				// color: white;
        background-color: #fafafa;
        padding: 8rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 8rpx;
			}
			.conform {
				// background-color: #ff6000;
				color: white;
				padding: 8rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 8rpx;
        width: 60rpx;
        height: 60rpx;
        .locations{
          width: 50rpx;
          height: 50rpx;
        }
			}
		}

		.map-box {
			height: 60%;
			// background-color: pink;
			#map {
				width: 100%;
				height: 100%;
			}
			::v-deep  .amap-logo {
				display: none !important;
			}
			::v-deep  .amap-copyright {
				display: none !important;
			}
		}

		.content {
			position: fixed;
			bottom: 0;
			border-radius: 24rpx 24rpx 0 0;
			height: 42%;
			width: 100%;
			background: white;
			box-sizing: border-box;
			padding: 24rpx;
			.search {
				width: 100%;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				&>view {
					width: 88%;
					height: 64rpx;
					background: #F4f4f4;
					border-radius: 14rpx;
					box-sizing: border-box;
					padding: 8rpx 24rpx;
					display: flex;
					flex-direction: row;
					align-items: center;
					image {
						width: 30rpx;
						height: 25rpx;
					}
					input {
						margin-left: 8rpx;
						flex: 1;
					}
				}
			}

			.main  {
				margin-top: 20rpx;
				height: calc(100% - 88rpx);
				// background: pink;
				overflow-y: auto;
				&>view {
					box-sizing: border-box;
					padding: 20rpx;
					width: 100%;
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: space-between;
					.detail {
						color: #707070;
					}
				}
			}
		}
	}
 ::v-deep  #__vconsole .vc-switch{
    z-index: 20000;
  }
</style>
